/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.master.opname.item;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.entities.MasterUnit;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.entities.PosTransactionOpnameItem;
import com.ronsicecream.pos.entities.PosTransactionOpnameItemDetail;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.master.opname.itemdetail.OpnameItemDetail;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpSession;

/**
 *
 * @author user
 */
public class OpnameItem extends Page {

    private Field opnameId;
    private Field opnameNumber;
    private Field opnameDate;
    private Field opnameKnownBy;
    private Field opnameDescription;
    private Field opnameTimestamp;
//    private Field opnameRegionalId;
//    private Field opnamePosUnitId;
    private Field opnameUnitTypeId;
    private Field opnameUnitId;
    private Field opnameUserId;

    public OpnameItem() {
        super();

        setTheClass(PosTransactionOpnameItem.class);

        setPageDetail(OpnameItemDetail.class);


        opnameId = new Field();
        opnameId.setName("opnameId");
        opnameId.setCaption(" id");
        //opnameId.setInfo("opname id");
        opnameId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        opnameId.setInputProperties(" size=\"20\"");
        getFields().add(opnameId);

        opnameNumber = new Field();
        opnameNumber.setName("opnameNumber");
        opnameNumber.setCaption("number");
        opnameNumber.setRequired(true);
        opnameNumber.setListProperties(" align=\"left\" width=\"20%\" nowrap");
        opnameNumber.setInputProperties(" size=\"30\" readonly");
        getFields().add(opnameNumber);

        opnameDate = new Field();
        opnameDate.setName("opnameDate");
        opnameDate.setCaption("date");
        opnameDate.setRequired(true);
        opnameDate.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        opnameDate.setInputProperties(" size=\"8\"");
        opnameDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(opnameDate);

        opnameKnownBy = new Field();
        opnameKnownBy.setName("opnameKnownBy");
        opnameKnownBy.setCaption("known by");
        opnameKnownBy.setRequired(true);
        opnameKnownBy.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        opnameKnownBy.setInputProperties(" size=\"20\"");
        getFields().add(opnameKnownBy);

        opnameDescription = new Field();
        opnameDescription.setName("opnameDescription");
        opnameDescription.setCaption("description");
        //opnameDescription.setInfo("opname description");
        opnameDescription.setListProperties(" width=\"30%\"");
        opnameDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        opnameDescription.setInputType(Field.INPUT_TEXT_AREA);
        opnameDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(opnameDescription);

        opnameTimestamp = new Field();
        opnameTimestamp.setName("opnameTimestamp");
        opnameTimestamp.setCaption("timestamp");
        //opnameTimestamp.setInfo("opname timestamp");
        opnameTimestamp.setListProperties(" align=\"center\"  nowrap");
        opnameTimestamp.setInputProperties(" size=\"12\"");
        //opnameTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(opnameTimestamp);

//        opnameRegionalId = new Field();
//        opnameRegionalId.setName("opnameRegionalId");
//        opnameRegionalId.setCaption("regional");
//        opnameRegionalId.setRequired(true);
//        opnameRegionalId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
////        opnameRegionalId.setInputProperties(" size=\"20\"");
//        opnameRegionalId.setInputType(Field.INPUT_COMBO_BOX);
//        getFields().add(opnameRegionalId);

        opnameUnitId = new Field();
        opnameUnitId.setName("opnameUnitId");
        opnameUnitId.setCaption("unit");
        //opnameUnitId.setInfo("pos transaction opname item detail collection");
        opnameUnitId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        opnameUnitId.setInputProperties(" size=\"20\"");
        getFields().add(opnameUnitId);

//        opnamePosUnitId = new Field();
//        opnamePosUnitId.setName("opnamePosUnitId");
//        opnamePosUnitId.setCaption("unit");
//        //opnameUnitId.setInfo("pos transaction opname item detail collection");
//        opnamePosUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
////        opnamePosUnitId.setInputProperties(" size=\"20\"");
//        opnamePosUnitId.setInputProperties(Field.INPUT_COMBO_BOX);
//        getFields().add(opnamePosUnitId);

        opnameUnitTypeId = new Field();
        opnameUnitTypeId.setName("opnameUnitTypeId");
        opnameUnitTypeId.setCaption("Unit Type");
        //opnameUnitId.setInfo("pos transaction opname item detail collection");
        opnameUnitTypeId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        opnameUnitTypeId.setInputProperties(Field.INPUT_COMBO_BOX);
        getFields().add(opnameUnitTypeId);

        opnameUserId = new Field();
        opnameUserId.setName("opnameUserId");
        opnameUserId.setCaption("user");
        //opnameUserId.setInfo("pos transaction opname item detail collection");
        opnameUserId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        opnameUserId.setInputProperties(Field.INPUT_COMBO_BOX);
        getFields().add(opnameUserId);


        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(opnameNumber);
        getFieldsAdd().add(opnameDate);
//        getFieldsAdd().add(opnameRegionalId);
//        getFieldsAdd().add(opnameUnitTypeId);
        getFieldsAdd().add(opnameKnownBy);
        getFieldsAdd().add(opnameDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(opnameNumber);
//        getFieldsEdit().add(opnameRegionalId);
//        getFieldsEdit().add(opnameUnitTypeId);
        getFieldsEdit().add(opnameDate);
        getFieldsEdit().add(opnameDescription);

        getFieldsList().clear();
        getFieldsList().add(opnameNumber);
        getFieldsList().add(opnameDate);
        getFieldsList().add(opnameUnitTypeId);
        getFieldsList().add(opnameKnownBy);
        getFieldsList().add(opnameDescription);

        getFieldsView().clear();
        getFieldsView().add(opnameNumber);
//        getFieldsView().add(opnameRegionalId);
//        getFieldsView().add(opnamePosUnitId);
        getFieldsView().add(opnameUnitTypeId);
        getFieldsView().add(opnameDescription);
        getFieldsView().add(opnameKnownBy);
        getFieldsView().add(opnameUserId);
        getFieldsView().add(opnameUnitId);
        getFieldsView().add(opnameTimestamp);

        setController(new OpnameItemController(this));
        setExportList(getClass().getResourceAsStream("OpnameList.jasper"));
        setExport(getClass().getResourceAsStream("Opname.jasper"));
    }

//    @Override
//    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
//        opnameDate.setFormater(DateFormatter.getInstanceDate(this));
//        opnameTimestamp.setFormater(DateFormatter.getInstanceDateTime(this));
//    }
    @Override
    public void beforeAdd() {
        opnameNumber.setDefaultValue(generate());
    }

    class OpnameItemController extends Controller {

        public OpnameItemController(Page page) {
            super(page);
            setOrder(opnameTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data) {
            PosTransactionOpnameItem opname = (PosTransactionOpnameItem) data;
            opname.setOpnameNumber(generate());
            opname.setOpnameUnitId(getCurrentUnit());
            opname.setOpnameUserId(getCurrentUser());
//            opname.setOpnameDate(Utility.getTimestamp());
            opname.setOpnameTimestamp(Utility.getTimestamp());

        }

        @Override
        public void afterInsert(Object data, List list) {
            EntityManager em = getEntityManager();
            try {
                em.getTransaction().begin();
                PosTransactionOpnameItem opname = (PosTransactionOpnameItem) data;
                 System.out.println("Jose --->>>obname :" + opname);
//                PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
//                        + " WHERE t.unitUnitTypeId.unitTypeId= " + opname.getOpnameId().getUnitTypeId()
//                        + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId())
//                        //                        + " AND t.unitRegionalId.regionalId="+opname.getOpnameRegionalId().getRegionalId()
//                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
                
                for (Object detail : list) {
                    PosTransactionOpnameItemDetail opnameDetail = (PosTransactionOpnameItemDetail) detail;
                    PosMasterItemStock stock = Item.getStockItem(em, opnameDetail.getOpnameDetailItemId(), opname.getOpnameUnitId());
                    PosTransactionItemStock itemStock = new PosTransactionItemStock();
                    itemStock.setItemStockId(Sequence.next(itemStock));
                    itemStock.setItemStockItemId(opnameDetail.getOpnameDetailItemId());
                    System.out.println("unittt :" + opname.getOpnameUnitId());
                    itemStock.setItemStockRegionalId(opname.getOpnameRegionalId());
                    itemStock.setItemStockUnitId(opname.getOpnameUnitId());
                    itemStock.setItemStockPosUnitId(opname.getOpnamePosUnitId());
                    itemStock.setItemStockStatusId(opnameDetail.getOpnameDetailStatusId());
                    itemStock.setItemStockType("6");
                    opnameDetail.setOpnameDetailOldValue(stock.getItemStockValue());
                    itemStock.setItemStockLast(stock.getItemStockValue());
                    itemStock.setItemStockCurrent(opnameDetail.getOpnameDetailNewValue());
                    itemStock.setItemStockValue(opnameDetail.getOpnameDetailNewValue());
                    itemStock.setItemStockUserId(getCurrentUser());
                    itemStock.setItemStockTimestamp(Utility.getTimestamp());
                    em.persist(itemStock);
                    stock.setItemStockValue(itemStock.getItemStockCurrent());
                    stock.setItemStockTimestamp(Utility.getTimestamp());
                }
                em.getTransaction().commit();
            } catch (Exception e) {
                Logger.getInstance().log(e);
                System.out.println("Eroorrrr :" + e);
            }
        }
    }

    public String generate() {
        HttpSession session = getRequest().getSession();
        String unitCode = ((MasterUnit) session.getAttribute("bynga.unit")).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionOpnameItem opname = (PosTransactionOpnameItem) getEntityManager().createQuery("SELECT t FROM PosTransactionOpnameItem t WHERE t.opnameNumber LIKE '%/" + unitCode + "/OPN/%/" + year + "' ORDER BY t.opnameTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(opname.getOpnameNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/OPN/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/OPN/" + month + "/" + year;
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Opname Item"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
